<template>
  <div>
    <div class="container">
      <Nav></Nav>
      <div class="main">
        <div class="main-top">
          <div class="logo-nav">
            <el-avatar :size='100'  >{{headphoto}}</el-avatar>
            <div class="name">{{userInfoForm.username}}</div>
            <el-menu
              style="width: 100%;border:none"
              background-color="#fff"
              text-color="#333"
              active-text-color="#F56C6C"
              @select='getData'
            >
              <el-menu-item index="1">
                <i class="el-icon-location"></i>
                <span slot="title"> 个人资料</span>
              </el-menu-item>
              <el-menu-item index="2">
                <i class="el-icon-menu"></i>
                <span slot="title">我会烧的菜</span>
              </el-menu-item>
              <el-menu-item index="3">
                <i class="el-icon-document"></i>
                <span slot="title">发布菜品</span>
              </el-menu-item>
            </el-menu>
          </div>
          <div class="info">
            <div v-if="activeIndex == 1">
              <el-descriptions  title="个人信息" :column="3">
                <template slot="extra">
                  <el-button type="primary" size="small" @click="changeInfo">修改用户信息</el-button>
                </template>
                <el-descriptions-item label="用户名">{{username}}</el-descriptions-item>
                <el-descriptions-item label="手机号码">{{phone}}</el-descriptions-item>
                <el-descriptions-item label="地址">{{address}}</el-descriptions-item>
                <el-descriptions-item label="性别">{{sex}}</el-descriptions-item>
                <!-- <el-descriptions-item label="备注">
                  <el-tag size="small">学校</el-tag>
                </el-descriptions-item> -->
                <el-descriptions-item label="邮箱">{{email}}</el-descriptions-item>
                <!-- <el-descriptions-item label="个性签名">{{userInfoForm.bio}}</el-descriptions-item> -->
              </el-descriptions>
            </div>
            <div v-if="activeIndex == 2" style="cursor: pointer">
              <div style="font-size:16px;font-weight:700;margin-bottom:20px;text-align:left">已发布菜谱</div>
              <!-- <div v-for="(menu,key) in menuList" :key="key">
                <div class="menu" @click="goMenuDetail(menu)">
                  <el-empty :image='menu.main_image' description="暂无图片"></el-empty>
                  <div class="info">
                    <div style="font-size:16px;font-weight:700;">菜名：{{menu.name}}</div>
                    <div class="desc">介绍：{{menu.goods}}</div>
                    <div>主料：{{menu.main_material}}</div>
                    <div>配料：{{menu.sub_material}}</div>
                  </div>
                </div>
                <el-divider ></el-divider>
              </div>    -->
              <div>
                <el-table size="mini" border style="width: 100%" height="600px" :data="data" >
                  <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
                  <el-table-column prop="cname" label="菜系" width="120" align="center"></el-table-column>
                  <el-table-column prop="name" label="菜名" width="120" align="center"></el-table-column>
                  <el-table-column prop="photo" label="图片" width="180" align="center"></el-table-column>
                  <el-table-column prop="introduction" label="简介" width="180" align="center"></el-table-column>
                  <el-table-column prop="prices" label="价格" width="120" align="center"></el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
                      <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row.id)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <!--  layout:分页条布局  prev:上页按钮  pager:页码  next：下一页按钮  page-size: 每页显示数量  total：总条目数-->
              <div class="pagination">
                <el-pagination background :current-page="currentPage" :page-size="pageSize" :total="total"
                  layout="total,prev,pager,next" @current-change="handleCurrentChange"></el-pagination>
              </div>
            </div>
            <!-- 编辑菜信息 -->
            <el-dialog title="更改菜的信息" :append-to-body="true" :visible.sync="editVisible" width="400px" center>
              <el-form :model="form" ref="form" label-width="80px" :rules="rules">
                <el-form-item prop="id" label="编号" size="mini">
                  <el-input v-model="form.id" placeholder="编号"></el-input>
                </el-form-item>
                <el-form-item prop="name" label="菜名" size="mini">
                  <el-input v-model="form.name" placeholder="菜名"></el-input>
                </el-form-item>
                <el-form-item prop="prices" label="价格" size="mini">
                  <el-input v-model="form.prices" placeholder="价格"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="简介" size="mini">
                  <el-input v-model="form.introduction" placeholder="简介"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer">
                <el-button size="mini" @click="editVisible = false">取消</el-button>
                <el-button size="mini" type="primary"  @click="editSave">确定</el-button>
              </span>
            </el-dialog>
            <el-dialog title="删除菜品" :append-to-body="true" :visible.sync="delVisible" width="300px" center>
              <div>删除不可恢复，是否确定删除？</div>
              <span slot="footer">
                <el-button size="mini" type="primary" @click="delVisible = false">取消</el-button>
                <el-button size="mini" type="danger" @click="deleteRow">确定</el-button>
              </span>
            </el-dialog>

            <div v-if="activeIndex == 3" style="cursor: pointer">
              <div style="font-size:16px;font-weight:700;margin-bottom:20px;text-align:left">待审核菜谱</div>
              <el-form :model="formDish" ref="formDish" label-width="80px" :rules="rules">
                <el-form-item prop="cid" label="菜系" size="mini" style="width: 200px">
                  <el-select v-model="formDish.cid" placeholder="菜系">
                    <el-option label="川菜" value="1"></el-option>
                    <el-option label="粤菜" value="2"></el-option>
                    <el-option label="湘菜" value="3"></el-option>
                    <el-option label="闽菜" value="4"></el-option>
                    <el-option label="苏菜" value="5"></el-option>
                    <el-option label="浙菜" value="6"></el-option>
                    <el-option label="鲁菜" value="7"></el-option>
                    <el-option label="徽菜" value="8"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="name" label="菜名" size="mini" style="width: 200px">
                  <el-input v-model="formDish.name" placeholder="菜名"></el-input>
                </el-form-item>
                <el-form-item prop="prices" label="价格" size="mini" style="width: 200px">
                  <el-input v-model="formDish.prices" placeholder="价格"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="简介" size="mini" style="width: 200px">
                  <el-input v-model="formDish.introduction" placeholder="简介"></el-input>
                </el-form-item> 
                <el-form-item prop="photo" label="照片" size="mini" style="width: 200px">
                  <el-input v-model="formDish.photo" placeholder="照片"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size="mini" @click="editVisible = false">重置</el-button>
                    <el-button size="mini" type="primary"  @click="commitDish">提交</el-button>
                </el-form-item>
              </el-form>            
            </div>
            <div style="position:absolute;bottom:0px;right:10px;display:flex">
              <el-button size='small' type="success" style="width:100%" @click="changeMaster">升级为师傅</el-button>
              <el-button size='small' type="primary" style="width:100%" @click="resetPasswordFunc">重置密码</el-button>
              <el-button size='small' type="danger" style="width:100%" @click="logout">退出登录</el-button>
            </div>
          </div>
        </div>
        
      </div>
      <el-dialog
        title="修改用户信息"
        :visible.sync="isChangeUserInfo">
        <el-form :model="userInfoForm" :rules="rules" ref="userInfoForm" label-width="100px" >
          <el-form-item label="用户名" prop="username" >
            <el-input v-model="userInfoForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userInfoForm.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address" >
            <el-input v-model="userInfoForm.address" placeholder="请输入详细地址 比如3层207"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isChangeUserInfo = false">取 消</el-button>
          <el-button type="primary" @click="confirmInfoChange">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="升级为师傅填写信息"
        :visible.sync="isChangeMasterInfo">
        <el-form :model="masterInfoFrom" ref="masterInfoFrom"  label-width="100px" >
          <el-form-item label="真实姓名" prop="name" >
            <el-input v-model="masterInfoFrom.name" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isChangeMasterInfo = false">取 消</el-button>
          <el-button type="primary" @click="confirmMasterChange">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog
        width='30%'
        title="重置密码"
        :visible.sync="resetPasswordFlag">
        <el-input  size='small' v-model="phone" placeholder="请输入注册手机号" type='number'></el-input>
        <el-input  size='small' style="margin-top:10px" v-model="resetPassword" placeholder="请输入重置密码" show-password></el-input>
        <el-input  size='small' style="margin-top:10px" v-model="confirmResetPassword" placeholder="请再次输入重置密码" show-password></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button  size='small' @click="resetPasswordFlag = false">取 消</el-button>
          <el-button  size='small' type="primary" @click="confirmChange">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import store from '@/store'
import Nav from '@/components/nav'
import { mapGetters } from "vuex"; // mapGetters从整个工程其他地方获取数据
import { updatePassword ,updateInfo,changeMaster,getMasterCooking,updateDishAndMaster,deleteHDish,commitInfo_Dish} from "../../api/index";
import { mixin } from "../../mixins";
export default {
  components:{
    Nav
  },
  mixins: [mixin],
  data(){
    return{
      activeIndex:1,
      isChangeUserInfo:false,
      resetPasswordFlag:false,
      isChangeMasterInfo:false,
      editVisible: false,//编辑弹窗是否显示
      delVisible: false, //删除弹窗是否显示
      userInfoForm:{
        username:'',//用户名
        phone:'',//手机号码
        address:'',//地址
      },
      masterInfoFrom:{
        name:'',//真实姓名
        id:'',//用户编号
      },
      rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入手机号码', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入详细地址 比如3层207', trigger: 'blur' }
          ],
      },
      resetPassword:'',
      confirmResetPassword:'',
      // phone:null,
      menuList:[],//菜单列表
      //发布的菜的表格中的数据
      tableData:[],//数据库表数据
      //分页设置
      currentPage: 0,//当前页
      pageSize: 0,//分页的每页显示多少个
      total: 0,//总条数
      //编辑框的数据绑定model
      form: {
        id: "",
        name: "",
        prices:"",
        introduction: ""
      },
      idx:"",//删除的编号
      //编辑框的数据绑定model
      formDish: {
        cid: "",
        name: "",
        prices:"",
        introduction: "",
        photo:"",
        mid:"",
      },
    }
  },
  
  computed: { // 监控数据的获取
    ...mapGetters([ "id", "mid","headphoto","username","phone","address","email","sex"]), //监控到的"username", "id", "phone"可以当做该页面的数据（和data里相同）
    data() {
      return this.tableData;//查找数据库数据
    },
  },
  //生命周期函数
  created() {
    this.getData();
  },
  methods:{
    confirmInfoChange(){
      let _this = this;
      updateInfo(_this.userInfoForm)
        .then((res) => {
          if (res) {
            _this.notify("修改成功", "success");
            setTimeout(function () {
              _this.$router.push({ path: "/login" });
            }, 2000);
          } else {
            _this.notify("修改失败", "error");
          }
        })
        .catch((err) => {
          _this.notify("修改失败", "error");
          this.loading = false;
        });
        this.isChangeUserInfo = false;
    },
    confirmMasterChange(){
      let _this = this;
      _this.masterInfoFrom.id = this.id;
      changeMaster(_this.masterInfoFrom)
        .then((res) => {
          if (res) {
            _this.notify("升级成功", "success");
           
          } else {
            _this.notify("升级失败", "error");
          }
        })
        .catch((err) => {
          _this.notify("升级失败", "error");
          this.loading = false;
        });
        this.isChangeMasterInfo = false;
    },
    
    changeInfo(){
      this.isChangeUserInfo = true;
    },
    changeMaster(){
      this.isChangeMasterInfo = true;
    },
    //获取当前页
   handleCurrentChange(val) {
      this.currentPage = val;
      this.getData(); 
    },
    //查询所有师傅会做的菜  以及分页
    getData(index){
      this.activeIndex = index;
      // this.$message(this.mid,"success")
      if(index == '2'){//已发布菜谱
        this.tableData = [],
        getMasterCooking(this.currentPage,this.mid).then((res) => {
          this.tableData = res.records;
          this.pageSize = res.size;
          this.total = res.total;
        })
      }
      // if(index == '3'){//待审核菜谱
      //   this.$http.get('/healthy/public/api/menu/UserMenuList',{
      //         status:'1',
      //         id:this.userInfoForm.id,
      //       })
      //       .then(
      //         (res)=>{
      //           let resData = res.data;
      //           if(resData.code == 1){
      //             this.$message({
      //               message: '获取已发布菜谱成功',
      //               type: 'success'
      //             });
      //             this.menuList = resData.data.data;
      //           }else{
      //             this.$message.error(resData.msg);
      //           }
      //         }
      //       ).catch(
      //         (err)=>{
      //           console.log(err);
      //           this.$message.error('网络异常');
      //         }
      //       )
      // }
    },
    //弹出编辑页面
    handleEdit(row) {
      this.editVisible = true;
      this.form = {
        id: row.id,
        name: row.name,
        prices: row.prices,
        introduction: row.introduction,
      };
    },
    //保存修改用户信息
    editSave() {
      updateDishAndMaster(this.form)
        .then((res) => {
          if (res) {
            this.notify("修改成功", "success");
            this.getData();
          } else {
            this.notify("修改失败", "error");
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.editVisible = false;
    },
    
    handleDelete(idx){
      this.delVisible = true;
      this.idx = idx;
    },
    deleteRow(){
      deleteHDish(this.idx).then((res) => {
        if (res) {
          this.notify("删除成功", "sucess");
          this.delVisible = false;
          this.getData();
        } else {
          this.notify("删除失败", "error");
        }
      })
      this.delVisible = false;
    },
    //提交菜品信息。
    commitDish(){
      this.formDish.mid = this.mid;
      commitInfo_Dish(this.formDish)
        .then((res) => {
          if (res) {
            this.notify("提交成功", "success");
            this.getData();
          } else {
            this.notify("提交失败", "error");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    
    logout(){
      localStorage.healthyToken = '';
      localStorage.healthyUserInfo = '';
      this.$router.push({ path: "/login" });
    },
    resetPasswordFunc(){
      this.resetPassword = '';
      this.resetPasswordFlag = true;
    },
    confirmChange(){
      if(this.resetPassword == ''){
        this.$message.error('新密码不能为空')
        return
      }
      if(this.confirmResetPassword != this.resetPassword){
        this.$message.error('两个密码不一致请重新输入')
        return
      }
      let params = new URLSearchParams();
      params.append('id', this.id);           //用户id
      params.append('password', this.resetPassword); //修改的密码
      updatePassword(params)
      .then((res)=>{
        let _this = this
        if (res) {
             _this.notify("修改成功", "success");
             this.$router.push({ path: "/login" });
          } else {
            _this.notify("修改失败", "error");
          }
        })
        .catch((err) => {
          _this.notify("用户名或密码错误", "error");
        });
      this.resetPasswordFlag = false;
    },
    // resetPasswordPost(data){
    //   this.$http.post('/healthy/public/api/user/resetpwd',data)
    //   .then(
    //     (res)=>{
    //       let resData = res.data;
    //       if(resData.code == 1){
    //         this.$message({
    //           message: resData.msg,
    //           type: 'success'
    //         });
    //         localStorage.healthyToken = '';
    //         this.$router.push({ path: "/login" });
    //       }else{
    //         this.$message.error(resData.msg);
    //       }
    //     }
    //   ).catch(
    //     (err)=>{
    //       console.log(err);
    //       this.$message.error('网络异常');
    //     }
    //   )
    // },
    postMenu(){
      this.$router.push({path:'/postMenu'});
    },
    goMenuDetail(menu){
      this.$router.push({path:'/menuDetail',query:{id:menu.id}});
    }
  }
};
</script>

<style scoped>
.container {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f1f1f1;
  overflow: auto;
}
.main{
  width: 1200px;
  box-sizing: border-box;
  padding: 20px;
  margin: 10px auto 0;
  border-radius: 12px;
  background-color: #fff;
}
.main-top{
  display: flex;
}
.logo-nav{
  width: 200px;
  min-width: 200px;
  border-right: 2px solid #f1f1f1;
  text-align: center;
  padding: 10px;
  padding-right: 20px;
  box-sizing: border-box;
}
.logo-nav .name{
  font-size: 20;
  font-weight: bold;
  margin: 10px;
}
.main-top .info{
  padding: 10px 20px;
  position: relative;
  width: 100%;
}
.menu{
  display: flex;
  height: 200px;
  padding: 10px;
  text-align: left;
}
.menu .info{
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
</style>